import appStore from '@/store';
import { RoutesMap, allRoutes, routes } from './routes';
import { createRouter, createWebHistory } from 'vue-router';
const router = createRouter({
  history: createWebHistory(),
  routes,
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition;
    } else {
      return { top: 0 };
    }
  },
});

let hasRoles = true;
router.beforeEach(async (to, from, next) => {
  if (to.path === '/') {
    next('/dashboard');
  }

  const routers = appStore.userStore.routers;
  if (hasRoles) {
    routers.forEach((route: RoutesMap) => {
      router.addRoute(route as any);
    });
    hasRoles = false;
    next({ ...to, replace: true });
  } else {
    next();
  }
});

export default router;
